package xyz.penghaonan.wificonnect.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.penghaonan.appframework.AppDelegate;
import com.penghaonan.appframework.utils.WeakObservableList;

import static android.content.Context.BIND_AUTO_CREATE;

public class ServiceHelper {

    private final WeakObservableList<P2PServiceStateListener> stateListenerList = new WeakObservableList<>();
    private ServiceBinder binder;

    public interface P2PServiceStateListener {
        void onStateChanged(boolean enable);
    }

    private boolean isServiceRunning;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder = (ServiceBinder) iBinder;
            AppDelegate.post(new Runnable() {
                @Override
                public void run() {
                    isServiceRunning = true;
                    stateListenerList.iterate(new WeakObservableList.OnIterator<P2PServiceStateListener>() {
                        @Override
                        protected boolean onIterator(P2PServiceStateListener item) {
                            item.onStateChanged(isServiceEnable());
                            return false;
                        }
                    });
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            binder = null;
            AppDelegate.post(new Runnable() {
                @Override
                public void run() {
                    isServiceRunning = false;
                    stateListenerList.iterate(new WeakObservableList.OnIterator<P2PServiceStateListener>() {
                        @Override
                        protected boolean onIterator(P2PServiceStateListener item) {
                            item.onStateChanged(isServiceEnable());
                            return false;
                        }
                    });
                }
            });
        }
    };


    public void addStateListener(P2PServiceStateListener listener) {
        stateListenerList.addListener(listener);
    }

    public void removeStateListener(P2PServiceStateListener listener) {
        stateListenerList.removeListener(listener);
    }

    public void start() {
        AppDelegate.getApp().bindService(new Intent(AppDelegate.getApp(), MainService.class), serviceConnection, BIND_AUTO_CREATE);
    }

    public void stop() {
        try {
            AppDelegate.getApp().unbindService(serviceConnection);
        } catch (Exception e) {
        }
    }

    public void updateNotification() {
        if (binder != null) {
            binder.updateNotification();
        }
    }

    public boolean isServiceEnable() {
        return isServiceRunning;
    }
}
